package com.ruoyi.web.cp.service;

import cn.hutool.core.date.DateUtil;
import cn.hutool.core.text.CharSequenceUtil;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import lombok.RequiredArgsConstructor;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import java.util.*;

@Slf4j
@Service
@RequiredArgsConstructor
public class Ssq2Service {
    private static final String ISSUE = "issue";
    private static final String APPID_1000009 = "1000009";
    private final HttpService httpService;
    private final WinxinService winxinService;


    public void getSsqList(String ticketId, String name, Map<String, Object> maxMap) {
        String key = ticketId + "_" + name;
        String format = DateUtil.format(new Date(), "mm");

        if (format.equals(maxMap.get(key))) {
            return;
        }

        int currentMinute = Integer.parseInt(format); // 当前分钟数

        // 根据不同 ticketId 设置执行规则
        boolean shouldExecute = false;

        if ("39".equals(ticketId)) {
            // ticketId=39: 每分钟执行一次
            shouldExecute = true;
        } else if ("49".equals(ticketId)) {
            // ticketId=49: 只有在分钟数是 5 的倍数时执行
            shouldExecute = (currentMinute % 5 == 0);
        }

        // 如果不符合执行条件，则返回 maxIssue
        if (!shouldExecute) {
            return;
        } else {
            maxMap.put(key, format);
        }
        log.info("开始执行 ticketId:{},name:{}", ticketId, name);
        JSONObject data = httpService.sendLeyuCpList(ticketId, "100");
        if ("0".equals(data.getString("code"))) {
            JSONArray items = data.getJSONArray("data");
            String blue = getBlue(items, 0);
            String blue1 = getBlue(items, 1);
            String blue2 = getBlue(items, 2);
            String blue3 = getBlue(items, 3);
            judgeContinueMaxBlue(items, 2, name);
            judgeContinueSameBlue(items, name, blue, blue1, blue2);
            judgeContinueSameBlue4(items, name, blue, blue1, blue2, blue3);
            judgeContinueSameZh(items, name, 12);
        }
    }


    private Map<String, Integer> initCodes() {
        Map<String, Integer> nums = new HashMap<>();
        for (int i = 1; i < 17; i++) {
            nums.put(CharSequenceUtil.padPre(i + "", 2, "0"), 0);
        }
        return nums;
    }

    private void judgeContinueSameZh(JSONArray items, String name, int count) {
        List<String> zs = Arrays.asList("01", "02", "03", "05", "07", "09", "11", "13");
        int flag = 0;
        for (int i = 0; i < count; i++) {
            JSONObject item = items.getJSONObject(i);
            String code = item.getString("code").split(",")[6];
            if (zs.contains(code)) {
                flag++;
            }
        }
        if (flag == count || (flag == 0)) {
            String msg = CharSequenceUtil.format("{},{},连续质合,{}", name, items.getJSONObject(0).getString(ISSUE), count);
            log.info(msg);
            winxinService.sendTextMessage(APPID_1000009, msg);
        }
    }

    private void judgeContinueSameBlue4(JSONArray items, String name, String blue, String blue1, String blue2, String blue3) {
        boolean boo1 = blue.equals(blue1) && blue.equals(blue2) && blue.equals(blue3);
        boolean boo2 = blue.equals(blue1) && blue2.equals(blue3);
        int num1 = Math.abs(Integer.parseInt(blue) - Integer.parseInt(blue1));
        int num2 = Math.abs(Integer.parseInt(blue1) - Integer.parseInt(blue2));
        int num3 = Math.abs(Integer.parseInt(blue2) - Integer.parseInt(blue3));

        boolean boo3 = num1 == num2 && num2 == num3;

        if (boo1 || boo2) {
            String msg = CharSequenceUtil.format("{},{},连续重号", name, items.getJSONObject(0).getString(ISSUE));
            log.info(msg);
            winxinService.sendTextMessage(APPID_1000009, msg);
        } else if (boo3) {
            String msg = CharSequenceUtil.format("{},{},连续间隔相同", name, items.getJSONObject(0).getString(ISSUE));
            log.info(msg);
            winxinService.sendTextMessage(APPID_1000009, msg);
        }
    }

    private void judgeContinueSameBlue(JSONArray items, String name, String blue, String blue1, String blue2) {
        String maxBlue = getMaxBlue(items, 1);
        log.info("name:{}, maxBlue:{}, blue:{},blue1:{},blue2:{}", name, maxBlue, blue, blue1, blue2);
        if (blue1.equals(blue2) && maxBlue.equals(blue)) {
            String msg = CharSequenceUtil.format("{},{},重号连最大", name, items.getJSONObject(0).getString(ISSUE));
            log.info(msg);
            winxinService.sendTextMessage(APPID_1000009, msg);
        }
    }

    private void judgeContinueMaxBlue(JSONArray items, int continueNum, String name) {
        int count = 0;
        for (int i = 0; i < continueNum; i++) {
            String maxBlue = getMaxBlue(items, i + 1);
            String blue = getBlue(items, i);
            log.info("name:{},maxBlue:{},blue:{}", name, maxBlue, blue);
            if (maxBlue.equals(blue)) {
                count++;
            }
        }
        if (count == continueNum) {
            String msg = CharSequenceUtil.format("{},{},连续最大", name, items.getJSONObject(0).getString(ISSUE));
            log.info(msg);
            winxinService.sendTextMessage(APPID_1000009, msg);
        }
    }

    private String getBlue(JSONArray items, int index) {
        return getBlue(items.getJSONObject(index));
    }

    private String getBlue(JSONObject item) {
        return item.getString("code").split(",")[6];
    }

    private String getMaxBlue(JSONArray items, int index) {
        Map<String, Integer> nums = initCodes();
        for (int i = items.size() - 1; i >= index; i--) {
            JSONObject item = items.getJSONObject(i);
            Iterator<String> iterator = nums.keySet().iterator();
            while (iterator.hasNext()) {
                String key = iterator.next();
                if (!key.equals(getBlue(item))) {
                    nums.put(key, nums.get(key) + 1);
                } else {
                    nums.put(key, 0);
                }
            }
        }
        //获取nums中value值最大的key
        return Collections.max(nums.entrySet(), Map.Entry.comparingByValue()).getKey();
    }

}
